import {handleActions as createReducer} from 'redux-actions'
import {addroductToLocalCart,saveCarts,deleteProductFromLocalCart,changeLocalProductNumber} from '../actions/cart.action'
const initialState = []

const handleAddroductToLocalCart = (state,action) => {
  
  const newState = JSON.parse(JSON.stringify(state))
  const product = newState.find(product => product.id === action.payload.id)
  if(product) {
    // 购物车有
    product.count = product.count + 1 
  }else {
    // 购物车没有 
    newState.push(action.payload)
  }
  return newState
}

const handleSaveCarts = (state,action) => action.payload

const handleDeleteProductFromLocalCart = (state,action) => {
  // 删除本地购车数据
  const newState = JSON.parse(JSON.stringify(state))
  newState.splice(action.payload,1)
  return newState
}
const handleChangeLocalProductNumber = (state,action) => {
  const newState = JSON.parse(JSON.stringify(state))

  const product = newState.find(product => product.id === action.payload.id)
  product.count = action.payload.count
  return newState
}
export default createReducer({
  // 将商品列表数据保存在本地store中
  [addroductToLocalCart]:handleAddroductToLocalCart,
  [saveCarts]: handleSaveCarts,
  [deleteProductFromLocalCart]:handleDeleteProductFromLocalCart,
  [changeLocalProductNumber]:handleChangeLocalProductNumber
},initialState)